package Server;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;

public class PackageHandler {
//	Map<String,String> versionMap = new HashMap<String,String>();
	
	Proxy proxy = null;
	final static int size=1024;
	public PackageHandler() {
	}
	
	public Map<String,String> getPackages(String type) {
		Map<String,String >ret = new HashMap<String,String>();
		try {
			int ByteRead=0;
			proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("sawebproxy00.nmp.nokia.com", 8080));
			HttpURLConnection con = null;
			if ( proxy == null )
				con = (HttpURLConnection) new URL("http://www.nic.funet.fi/pub/mirrors/ftp.debian.org/debian/dists/"+type+"/main/binary-i386/Packages.gz").openConnection();
			else
				con = (HttpURLConnection) new URL("http://www.nic.funet.fi/pub/mirrors/ftp.debian.org/debian/dists/"+type+"/main/binary-i386/Packages.gz").openConnection(proxy);
			byte[] buf = new byte[size];
			OutputStream out = new ByteArrayOutputStream();
			GZIPInputStream gzipInputStream = new GZIPInputStream(con.getInputStream());
			while ((ByteRead = gzipInputStream.read(buf)) > 0)
				out.write(buf, 0, ByteRead);
			gzipInputStream.close();
			String buffer[] = out.toString().split("\n");
			String name=null;
			String ver =null;
			for ( int i=0;i<buffer.length;i++) {
				if ( buffer[i].indexOf(": ") > 0 ) {
					String keys[]=buffer[i].split(": ");

					if ( keys[0].equals("Package") ) 
						name = keys[1];
					if ( keys[0].equals("Version") )
						ver = keys[1];
				}
				if ( buffer[i].length() == 0 || i == (buffer.length-1) ) 
					ret.put(name, ver);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}		
		return ret;
	}
	public Boolean readContent() {
		
		return false;
	}
	
}
